<!-- 主平台——用户编辑弹窗 -->
<template>
  <ele-modal
    width="680px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    :title="isUpdate ? '修改设备' : '添加设备'"
    @update:visible="updateVisible"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="82px">
      <el-row :gutter="15">
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item label="设备编号:" prop="equipmentCode">
            <el-input
              clearable
              :maxlength="20"
              :disabled="isUpdate"
              v-model="form.equipmentCode"
              placeholder="请输入设备编号"
            />
          </el-form-item>
          <el-form-item label="设备名称:" prop="equipmentName">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.equipmentName"
              placeholder="请输入设备名称"
            />
          </el-form-item>
          <!--<el-form-item label="所属代理:" prop="agentId">
            <el-select
              clearable
              class="ele-block"
              v-model="form.agentId"
              placeholder="请选择所属代理"
            >
              <el-option v-for="(i,j) in oemList" :key="j" :label="i.oemCode" :value="i.id"></el-option>
            </el-select>
          </el-form-item>-->
          <el-form-item label="设备状态:" prop="equipmentStatus">
            <el-select
              clearable
              class="ele-block"
              v-model="form.equipmentStatus"
              placeholder="请选择设备状态"
            >
              <el-option label="闲置中" :value="1" />
              <el-option label="使用中" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间:" prop="startTime">
           <el-date-picker
             type="date"
             class="ele-fluid"
             v-model="form.startTime"
             value-format="yyyy-MM-dd"
             placeholder="请选择有效期"
           />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { sm: 12 } : { span: 12 }">
          <el-form-item label="设备图片" class="check-star">
<!--            <div style="margin-left: -53px">-->
<!--              <div class="flex-between upload-class">-->
<!--                <div class="font-overflow">建议上传750px * 1334px尺寸</div>-->
<!--                <el-button type="primary" @click="uploadBj">上传图片</el-button>-->
<!--              </div>-->
            <ele-image-upload
              accept=".jpg,.jpeg,.png"
              :limit="1"
              :multiple="false"
              v-model="fileList"
              :auto-upload="false"
              :before-remove="onBeforeRemove"
            />
              <!--<el-upload
                class="avatar-uploader flex"
                :action="ossUrl"
                :show-file-list="false"
                :on-change="onUpload"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <div v-else class="avatar-uploader-icon flex-column">
                  <i class="el-icon-picture"></i>
                  <div>上传图片</div>
                </div>
              </el-upload>-->
            <div style="font-size: 12px;color: #ccc">建议图片尺寸为200*200</div>
<!--            </div>-->
          </el-form-item>
<!--          <el-form-item label="设备图片:" prop="equipmentPicture">-->
<!--            <el-input-->
<!--              clearable-->
<!--              :maxlength="100"-->
<!--              v-model.number="form.equipmentPicture"-->
<!--              placeholder="请输入设备图片"-->
<!--            />-->
<!--          </el-form-item>-->
        </el-col>
      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import EleImageUpload from 'ele-admin/es/ele-image-upload';
  import {getToken} from "@/utils/token-util";
  import {mainOssSignature} from "@/api/creatCenter/material";
  import { emailReg, phoneReg } from 'ele-admin';
  import RoleSelect from './role-select.vue';
  import { addUser, updateUser, checkExistence } from '@/api/equipmentManagement';
  import {JSEncrypt} from "jsencrypt";
  import axios from "axios";

  export default {
    components: { RoleSelect,EleImageUpload },
    props: {
      oemList:Array,
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object
    },
    data() {
      const defaultForm = {
        id:'',
        equipmentName: '',
        equipmentCode: '',
        equipmentStatus: '',
        activityName:'',
        startTime:'',
      };
      return {
        dataInfo:{},
        // 上传图片
        imageUrl: '',
        // 上传背景图片url
        fileList:[],
        defaultForm,
        // 表单数据
        form: { ...defaultForm },
        // 表单验证规则
        rules: {
          equipmentName: [
            {
              required: true,
              message: '请输入设备名称',
              trigger: 'blur'
            }
          ],
          equipmentCode: [
            {
              required: true,
              message: '请输入设备编号',
              trigger: 'blur'
            }
          ],
          equipmentPicture: [
            {
              required: true,
              message: '请选择设备图片',
              trigger: 'blur'
            }
          ],
          activityName: [
            {
              required: true,
              message: '请输入活动名称',
              trigger: 'blur'
            }
          ],
          startTime: [
            {
              required: true,
              message: '请选择开始时间',
              trigger: 'blur'
            }
          ],
          equipmentStatus: [
            {
              required: true,
              message: '请选择设备状态',
              trigger: 'blur'
            }
          ],
          agentId: [
            {
              required: true,
              message: '请选择所属代理',
              trigger: 'blur'
            }
          ],
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    methods: {
      /* 删除增加确认弹窗 */
      onBeforeRemove() {
        return new Promise((resolve, reject) => {
          this.$confirm('确定要删除吗?', '提示', {
            type: 'warning'
          })
            .then(() => {
              resolve();
            })
            .catch(() => {
              reject();
            });
        });
      },
      /* 上传 */
      onUpload(file) {
        // this.fileList=[]
        if (file.status !== 'ready') return // 阻止上传成功的触发
        this.fileList.push(file)
        console.log('onUpload=======this.fileList',this.fileList)
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        console.log('this.imageUrl',this.imageUrl,'his.fileList',this.fileList)
      },
      beforeAvatarUpload(file) {
        console.log('beforeAvatarUpload=======this.fileList',this.fileList)

        // const isJPG = file.type === 'image/jpeg';
        const isJPG = file.type;
        const isLt2M = file.size / 1024 / 1024 < 2;

        const extension1 = file.type === "image/jpg";
        const extension2 = file.type === "image/jpeg";
        const extension3 = file.type === "image/png";
        if (!extension1 && !extension2 && !extension3) {
          this.$message.error("请上传jpg 、png、jpeg 类型图片!");
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          console.log('this.fileList',this.fileList)
          if(this.fileList.length<=0) {
            this.$message.error('请上传设备图片');
            return
          }
          // 上传图片未修改，则直接调用‘保存设备’接口
          if(this.data && this.fileList[0].url==this.data.equipmentPicture){
            this.uploadApi()
          }
          else{
            this.uploadBj()
          }
        });
      },
      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
        // this.imageUrl=''
        if(this.fileList.length>0){
          this.fileList=[]
        }
      },
      async uploadBj(){
        /*if(!this.imageUrl) {
          this.$message.error('请选择文件后提交');
          return
        }*/
        // 获取文件上传签名数据
        this.dataInfo = await mainOssSignature()
        console.log('this.dataInfo',this.dataInfo)

        // for(let i=0;i<this.fileList.length;i++){
        // 单张图片上传，获取最后push的图片数值
        //   let file = this.fileList[this.fileList.length-1].raw
          let file = this.fileList[0].file

          let filename=file.name;
          let markIndex=(filename).lastIndexOf('.');
          let suffix=filename.substring(markIndex)    // 图片后缀(例.jpg)
          let date=new Date().getTime();    // 当前时间戳
          // 构建请求参数
          let param = new FormData()
          param.append("key", this.dataInfo.dir + date+suffix)
          param.append("policy", this.dataInfo.policy)
          param.append("OSSAccessKeyId", this.dataInfo.accessId)
          param.append("success_action_status", '200')
          // param.append("callback",  this.dataInfo.callback)     //回调（not)
          param.append("signature", this.dataInfo.signature)
          param.append("file", file, file.name)
          param.append('success_action_status', '200')
          let config = {
            headers: {
              'Access-Control-Allow-Origin': '*',
              'x-oss-callback-Authorization': getToken()
            }
          }
          axios.post(this.dataInfo.host, param, config).then(res => {
            if(res.status==200){
              console.log('this.dataInfo.host',this.dataInfo.host+'/'+date+suffix)
              let url=this.dataInfo.host+'/'+date+suffix;
              this.form.equipmentPicture=url;
              console.log(' this.form.equipmentPicture',this.form.equipmentPicture,'url',url)
              let type=file.type;
              this.fileList=[]
              this.uploadApi()
            }
            else{
              this.$message.error('上传失败');
            }

          }).catch(err => {
            console.log(err)
          })
        // }
      },
      // 保存接口
      uploadApi(){
        console.log("进入上传文件后===========")
        this.loading = true;
        const data = {
          ...this.form,
          // D音
          // agentId:1
        };
        console.log("this.form,",this.form)
        const saveOrUpdate = this.isUpdate ? updateUser : addUser;
        if (!this.isUpdate) {
          let encryptor = new JSEncrypt()
          let pk = this.$store.state.signature.pk
          encryptor.setPublicKey(pk)
          data.password = encryptor.encrypt(data.password)
        }
        saveOrUpdate(data)
          .then((msg) => {
            this.imageUrl=''
            this.loading = false;
            let hint= this.isUpdate ? '修改设备成功！' : '添加设备成功！'
            this.$message.success(hint);
            this.updateVisible(false);
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e);
          });
      }
    },
    watch: {
      visible(visible) {
        if (visible) {
          if (this.data) {
            // this.$util.assignObject(this.form, {
            //   ...this.data,
            //   password: null,
            //   sex: this.data.sex + ''
            // });
            this.form=this.data
            console.log("this.form=====",this.form,'this.data',this.data)
            let url= {url: this.data.equipmentPicture}
            this.fileList.push(url)
            console.log('his.fileList',this.fileList)
            // this.imageUrl=this.data.equipmentPicture
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
          }
        } else {
          this.$refs.form.clearValidate();
          this.form = { ...this.defaultForm };
        }
      }
    }
  };
</script>
<style scoped lang="less">
  .upload-class{
    margin: -16px 0 2px;
    div{
      line-height: 18px;
      color: #757575
    }
  }

  .avatar-uploader{
    margin: 0;
    padding: 0;
    outline: none;

    /* 修改 start*/
    border: 1px solid #D9D9D9;
    border-radius: 2px;
    /*end*/
    width: 88px;
    height: 88px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    color: #D9D9D9;
    text-align: center;
    i{
      font-size: 28px;
    }
    div{
      padding-top: 3px;
    }
  }
  .avatar {
    width: 90px;
    height: 90px;
    display: block;
  }
</style>
